<script setup lang="ts">
import { ref } from 'vue'
import { unique } from '@/utils'
import { Close, Stamp } from '@element-plus/icons-vue'
import type { TreeNodeData } from 'element-plus/es/components/tree-v2/src/types'
import type { TreeInstance } from 'element-plus/lib/components'
import { dayjs, ElMessage } from 'element-plus'
import { useWfApi } from '@/api/wf'
import emitter from '@/utils/mitt'

const { PostBatchApprovals } = useWfApi()

const emit = defineEmits(['fetch'])

const loading = ref(false)
const checkboxAll = ref(false)
const indeterminate = ref(false)
const dialogVisible = ref(false)
const defaultCheckedKeys = ref<string[]>([])
const items = ref<TypedAny[]>([])
const treeRef = ref<TreeInstance>()

const defaultProps = {
  children: 'children',
  label: 'label'
}
const trees = ref<TreeNodeData[]>([])

const open = (data: TypedAny[]) => {
  dialogVisible.value = true

  items.value = data

  const remarks = unique(data, 'remark').map((v) => v.remark)

  defaultCheckedKeys.value = data.map((v) => v.id)

  checkboxAll.value = true

  const list: TreeNodeData[] = []

  remarks.forEach((remark) => {
    const option = {
      label: remark,
      value: remark,
      children: data
        .filter((f) => f.remark === remark)
        .map((v) => {
          return {
            id: v.id,
            label: v.submit_user,
            detail: v.detail,
            value: v.id,
            submit_user: v.submit_user,
            ins_id: v.ins_id,
            submit_time: v.submit_time
          }
        })
    }

    list.push(option)
  })

  trees.value = list
}

const onCheckboxAll = (value: boolean) => {
  if (value) {
    treeRef.value?.setCheckedKeys(items.value.map((v) => v.id))
  } else {
    treeRef.value?.setCheckedKeys([])
  }
}

const onCheckChange = () => {
  const keys = (treeRef.value?.getCheckedKeys() || []).filter((f) => f)
  checkboxAll.value = keys.length === items.value.length
  indeterminate.value = checkboxAll.value ? false : !!keys.length
}

const onBatchApp = async () => {
  const list = (treeRef.value?.getCheckedKeys() || []).filter((f) => f)
  if (!list.length) {
    ElMessage.warning('未勾选可审批的行')
    return
  }
  loading.value = true
  try {
    await PostBatchApprovals({ rows: list })
    loading.value = false
    dialogVisible.value = false
    emit('fetch')
  } catch (e) {
    loading.value = false
  }
}

const onFetch = () => {
  console.log('onFetch')
  emit('fetch')
}

/**
 * 审批详情
 * @param data
 */
const onNeedViewApp = (data?: TypedAny) => {
  console.log(data)
  if (data) {
    emitter.emit('onNeedViewApp', {
      list: [data.value],
      running_id: data.value,
      onFetch
    })
  }
}

defineExpose({ open })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="70%"
    draggable
    overflow
    class="custom-dialog"
    append-to-body
    destroy-on-close
  >
    <template #header>
      <el-checkbox
        border
        v-model="checkboxAll"
        :indeterminate="indeterminate"
        @change="onCheckboxAll"
        >全选（{{ items.length }}）
      </el-checkbox>
    </template>
    <el-tree
      ref="treeRef"
      style="max-height: 80vh"
      :data="trees"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
      class="custom-tree"
      @check-change="onCheckChange"
    >
      <template #default="{ node, data }">
        <div class="py3">
          <span :class="{ 'color-warning': !data.detail }">{{ data.label }}</span>
          <span
            v-if="data.detail"
            class="color-primary cursor-pointer cursor-pointer-line"
            style="white-space: pre-wrap"
            @click="onNeedViewApp(data)"
          >
            - {{ data.detail }}
          </span>
          <span v-if="data.submit_time" class="color-info">
            - {{ dayjs(data.submit_time).format('YYYY-MM-DD') }}
          </span>
        </div>
      </template>
    </el-tree>
    <template #footer>
      <div class="custom-dialog-footer">
        <el-button @click="dialogVisible = false" :icon="Close" :loading="loading"
          >取消审批
        </el-button>
        <el-button type="primary" @click="onBatchApp" :icon="Stamp" :loading="loading"
          >同意审批
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.custom-tree {
  .el-tree-node__content {
    height: auto;
  }
}
</style>
